<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="showAddightDialog">添加角色</el-button>
      <el-table border stripe :data="rolesList">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['rowbottom',i1 == 0?'rowtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag  closable @close="remonRolesById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <el-row :class="[i2 == 0?'':'rowtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag closable @close="remonRolesById(scope.row, item2.id)" type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag closable @close="remonRolesById(scope.row, item3.id)" type="warning" v-for="item3 in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column
          width="180px"
          label="操作">
            <template
            slot-scope="slotScope">
              <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
                <el-button type="primary" icon="el-icon-edit" size="mini"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                <el-button @click="delUser(slotScope.row.id)" type="danger" icon="el-icon-delete" size="mini"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
                <el-button @click="showRightListdialog(slotScope.row)" type="warning" icon="el-icon-setting" size="mini"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限列表弹出框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="showRightsListDialog"
      width="50%"
      @close="clearDefaultId">
      <!-- 树形结构控件 -->
      <el-tree :default-checked-keys="defaultId" show-checkbox node-key="id" default-expand-all :data="rightsList" :props="rightsProps" ref="terrRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRightsListDialog = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色弹出框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRightDialog"
      width="50%"
      @close="modiDialog">
      <el-form :model="addRloseForm" :rules="addRloseRules" ref="addRloseRef" label-width="90px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRloseForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRloseForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRightDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRoleDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表数据
      rolesList: [],
      // 控制权限列表得展示与隐藏
      showRightsListDialog: false,
      // 权限数据列表
      rightsList: [],
      // 树形结构得数据绑定
      rightsProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中得权限
      defaultId: [],
      // 获取角色id
      roleId: '',
      // 添加角色对话框
      addRightDialog: false,
      // 添加角色表单数据
      addRloseForm: {
        roleName: '',
        roleDesc: ''
      },
      addRloseRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
    },
    // 删除权限
    async remonRolesById(role, rightId) {
      const confirmRemon = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRemon !== 'confirm') return this.$message.error('已取消删除')
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      role.children = res.data
    },
    // 分配权限列表
    async showRightListdialog(role) {
      this.roleId = role.id
      // 获取权限列表
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rightsList = res.data
      // 递归获取三级节点的id
      this.getLeafId(role, this.defaultId)
      this.showRightsListDialog = true
    },
    // 对话框关闭的时候清空默认权限数组
    clearDefaultId() {
      this.defaultId = []
    },
    // 运用递归获取三级节点的id
    getLeafId(node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach(item => {
        this.getLeafId(item, arr)
      })
    },
    // 分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.terrRef.getCheckedKeys(),
        ...this.$refs.terrRef.getHalfCheckedKeys()
      ]
      const keysStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: keysStr })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.showRightsListDialog = false
    },
    // 删除角色
    async delUser(id) {
      const confirmRemon = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRemon !== 'confirm') return this.$message.error('已取消删除')
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
    },
    // 点击添加角色按钮弹出对话框
    showAddightDialog() {
      this.addRightDialog = true
    },
    // 点击添加角色弹出框的确定按钮
    async addRoleDialog() {
      const { data: res } = await this.$http.post('roles', this.addRloseForm)
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.addRightDialog = false
      this.getRolesList()
      this.addRloseForm = {}
    },
    // 重置修改表单
    modiDialog() {
      this.$refs.addRloseRef.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
  .el-tag{
    margin: 7px;
  }
  .rowtop{
    border-top: 1px solid #eee;
  }
  .rowbottom{
    border-bottom: 1px solid #eee;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }
</style>
